package com.hjd.shop.serviceimpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hjd.shop.api.service.UserMoneyLogService;
import com.hjd.shop.constant.ShopCode;
import com.hjd.shop.constant.SystemUser;
import com.hjd.shop.constant.TableColumn;
import com.hjd.shop.constant.UserMoneyState;
import com.hjd.shop.entity.User;
import com.hjd.shop.entity.UserMoneyLog;
import com.hjd.shop.exception.CastException;
import com.hjd.shop.mapper.UserMapper;
import com.hjd.shop.api.service.UserService;
import com.hjd.shop.mapper.UserMoneyLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 胡江迪
 * @since 2020-10-13
 */
@Component
@Service(interfaceClass = UserService.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMoneyLogMapper userMoneyLogMapper;

    @Override
    public User getUserById(String id) {
        return this.getUserById(id);
    }

    @Override
    public void updateUserMoney(UserMoneyLog userMoneyLog) {
        //扣减余额
        User user = this.getUserById(userMoneyLog.getUserId());
        if(userMoneyLog.getMoneyLogType().equals(UserMoneyState.PAID_MONEY.getCode())){
            user.setUserMoney(user.getUserMoney().subtract(userMoneyLog.getUseMoney()))
                    .setModifyTime(new Date())
                    .setModifyUser(SystemUser.SYSTEM_USER);
        }
        //回退余额
        if(userMoneyLog.getMoneyLogType().equals(UserMoneyState.REFUND_MONEY.getCode())){
            Condition condition = Condition.create();
            condition.eq("order_id",userMoneyLog.getOrderId())
                    .eq("user_id",userMoneyLog.getUserId())
                    .eq("money_log_type",userMoneyLog.getMoneyLogType())
                    .eq(TableColumn.DELETE_FLAG_COLUMN,TableColumn.UN_DELETE);
            int count = userMoneyLogMapper.selectCount(condition);
            if(count<=0){
                CastException.cast(ShopCode.REFUND_LOG_NOT_EXIST);
            }
            //退款
            if(count>0){
                user.setUserMoney(user.getUserMoney().add(userMoneyLog.getUseMoney()));
                Condition userOfCondition = Condition.create();
                userOfCondition.eq("user_id",userMoneyLog.getUserId());
                this.update(user,userOfCondition);
                //把日志中的该条记录删除
                userMoneyLog.setDeleteFlag(TableColumn.DELETED);
                userMoneyLogMapper.updateById(userMoneyLog);
            }
        }
    }
}
